# frozen_string_literal: true

require_relative '../../../../../spec_helper'
require 'wpxf/modules'

describe Wpxf::Auxiliary::CpImageStoreArbitraryFileDownload do
  let(:subject) { described_class.new }

  before :each, 'setup subject' do
    allow(subject).to receive(:check_plugin_version_from_readme)
    allow(subject).to receive(:puts)
    allow(subject).to receive(:print)
    allow(subject).to receive(:emit_error)
  end

  it 'should return a {Wpxf::Module}' do
    expect(subject).to be_a Wpxf::Module
  end

  it 'should register a purchase_id option' do
    expect(subject.get_option('purchase_id')).to be_a Wpxf::IntegerOption
  end

  it 'should check the plugin version is 1.0.5' do
    subject.check
    expect(subject).to have_received(:check_plugin_version_from_readme)
      .with('cp-image-store', '1.0.6', '1.0.5')
      .exactly(1).times
  end

  it 'should not require authentication' do
    expect(subject.requires_authentication).to be false
  end

  it 'should configure a default remote file path' do
    expected = '../../../../wp-config.php'
    expect(subject.default_remote_file_path).to eql expected
  end

  it 'should configure the working directory' do
    expected = 'wp-content/plugins/cp-image-store/downloads'
    expect(subject.working_directory).to eql expected
  end

  it 'should configure the downloader url' do
    expect(subject.downloader_url).to eql subject.full_uri
  end

  it 'should configure the request params' do
    subject.set_option_value('remote_file', 'test.php')
    subject.set_option_value('purchase_id', 5)

    params = subject.download_request_params

    expect(params['action']).to eql 'cpis_init'
    expect(params['cpis-action']).to eql 'f-download'
    expect(params['purchase_id']).to eql '5'
    expect(params['cpis_user_email']).to match(/\w+@\w+\.com/)
    expect(params['f']).to eql 'test.php'
  end

  context 'if the download request returns code 302' do
    it 'should emit an error' do
      subject.handle_unexpected_http_code(302)
      expect(subject).to have_received(:emit_error)
        .with('The purchase ID appears to be invalid or reached the maximum number of downloads')
        .exactly(1).times
    end
  end

  it 'should GET the download request' do
    expect(subject.download_request_method).to eql :get
  end

  it 'should force the follow_http_redirection option to be false' do
    allow(subject).to receive(:scoped_option_change).and_call_original
    subject.run
    expect(subject).to have_received(:scoped_option_change)
      .with('follow_http_redirection', false)
      .exactly(1).times
  end
end
